﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Globalization;
using Barbar.UrlGuard.BL;
using System.Xml.Serialization;

namespace Barbar.UrlGuard.Dal {
  public class AuthenticationBasic : AuthenticationBase {
    private string m_UserName;
    private string m_Password;

    public string UserName {
      get { return m_UserName; }
      set { m_UserName = value; }
    }

    [XmlIgnore()]
    public string Password {
      get { return m_Password; }
      set { m_Password = value; }
    }

    public string EncryptedPassword {
      get {
        ISymmetricPasswordService passwordService = ServiceLocator.Instance.Resolve<ISymmetricPasswordService>();
        return passwordService.EncryptPassword(m_Password);
      }
      set {
        ISymmetricPasswordService passwordService = ServiceLocator.Instance.Resolve<ISymmetricPasswordService>();
        m_Password = passwordService.DecryptPassword(value);
      }
    }

    public override int AuthenticationTypeID {
      get { return AuthenticationType.Basic.AuthenticationTypeID; }
    }

    public override void SetWebRequest(WebRequest request) {
      if (request == null)
        throw new ArgumentNullException("request");

      CredentialCache cache = new CredentialCache();
      cache.Add(request.RequestUri, "Basic", new NetworkCredential(UserName, Password));
      request.Credentials = cache;

      string userNamePassword = string.Format(CultureInfo.InvariantCulture, "{0}:{1}", UserName, Password);
      request.Headers.Add("Authorization", "Basic" + Convert.ToBase64String(Encoding.UTF8.GetBytes(userNamePassword)));
    }

    public override object Clone() {
      AuthenticationBasic result = new AuthenticationBasic();
      result.UserName = m_UserName;
      result.Password = m_Password;
      return result;
    }
  }
}
